<?php
/**
 * Created by PhpStorm.
 * User: shkj
 * Date: 2020/7/13
 * Time: 23:17
 */

namespace app\api\model;


use think\Db;
use think\facade\Request;
use think\Model;
use app\api\service\Order as OrderService;
use app\lib\exception\UserException;
class Seckill extends Model
{
    public function seckill(){

        return $this->hasMany('seckillGoods','seckill_id','id');
    }
    public function goods(){

        return $this->belongsTo('Goods','goods_id','id');
    }


    public function order($data){
         if(isset($data['seckill_id'])){
             $res = model('seckill')->kills($data);
             if(!$res){
                return '失败';
            }
           
        }
    }

    public function kills($data){

        $goods = $data['goods'][0];
        $order_price = $data['order_price'];
        $uid = $data['uid'];
        $id = $data['goods'][0]["goods_id"]; //商品编号
        $seckill_id = $data["seckill_id"];//团购活动的编号

        if(!$id){

            return $this->insertlog(0);//记录失败日志
        }
//        $redis = $this->redis(); // 接入redis
      
        // redis()->connect('127.0.0.1',6379);
        $key = $seckill_id.'_goods_'.$id;
        $count=redis()->lpop($key); //减少库存，返回剩余库存数
        $seckill = db('seckill_goods')->field('sk_price,sk_num')->where('goods_id',$data['goods'][0]['goods_id'])->find();
        if(!$count || $seckill['sk_num']==0){ //库存为0
   

            redis()->del($key); // 删除库存列表
            $this->insertlog(0); //记录秒杀失败的 日志
           
            return_json(200,'失败',false);
        }else{// 有库存
            

            $data = Db::name("goods")->field("goods_title,title_thumb")->where("id",$id)->find();//查找商品
            if(!$data){

                return $this->insertlog(0); //商品不存在
            }else{
                  //1.创建订单          
                  //2.减库存
             // $info = array(
             //     ''
             // )  
             $orders = new OrderService();
             $order_no = $orders->makeOrderNo();
            
             //看看是不是vip
             $user = db('user')->field('vip')->where('id',$uid)->find();
             $vip = $user['vip'];

             if($vip){
                $order_total_price = $order_price* 0.85;
             }else{
                $order_total_price = $order_price;
             }

             $info = array( 
                'out_trade_no'=>$order_no,
                'user_id'=>$uid,
                'goods_total_price'=>$order_price,
                'order_total_price'=>$order_total_price,
                'total_count'=>1,
                'address'=> json_encode($this->getUserAddress(
                    $uid)),
                'create_time'=>time()


                );
            

            
                $res = db("seckill_goods")->where("seckill_id",$seckill_id)->where('goods_id',$id)->setDec("sk_num",1);
                

                 if($res){
                $orderId = db('order')->insertGetId($info);
                $o_goods = array(
                    'goods_id'=>$goods['goods_id'],
                    'goods_title'=>$goods['goods_title'],
                    'title_thumb'=>$goods['title_thumb'],
                    'goods_price'=>$goods['goods_price'],
                    'goods_attr_str'=>$goods['goods_attr_str'],
                    'goods_number' => $goods['goods_number'],
                    'order_id'=>$orderId
                    // 'goods_price'=>$
                    );
                db('order_goods')->insert($o_goods);
                $this->insertlog(); //记录成功的日志
                $status = array(
                   'order_no'=>$order_no,
                   'order_id'=>$orderId
                  );
               return_json(200,'成功',$status);
            }else{
                $this->insertlog(0);//记录失败的日志
               
                 return_json(200,'成功',false);
            }
            
             
            }

        }
    }


//拿地址
     private function getUserAddress($uid)
    {
        $userAddress = UserAddress::where('uid', '=', $uid)
            ->find();
        if (!$userAddress) {
            throw new UserException(
                [
                    'msg' => '用户收货地址不存在，下单失败',
                    'errorCode' => 60001,
                ]);
        }
        return $userAddress->toArray();
    }

// 记录日志 状态1成功 0失败
    function insertlog($status=1){
        return Db::name("log")->insertGetId(["count"=>1,"status"=>$status,"addtime"=>date('Y-m-d H:i:s')]);
    }

    public function select($pagenum,$pagesize){

      $map =[];
  $keywords = Request::param('query');
  if(!empty($keywords)){
    //条件2
   $map[] = ['sk_title','like','%'.$keywords.'%'];
}
        $res = db('seckill')->where($map)->page($pagenum,$pagesize)->select();
       
        $count = self::count();
        $info = array(
          'data'=>$res,
          'total'=>$count
      );
        if($info){
            return_json(200,'成功',$info);
        }else{
              return_json(400,'失败',false);
        }
    }


    public function add($data){
      $res = self::save($data);
       if($res){
            return_json(200,'成功',true);
        }else{
              return_json(400,'失败',false);
        }
    }

    public function del($id){
      $res = self::where('id',$id)->delete();
      if($res){
        db('seckill_goods')->where('seckill_id',$id)->delete();
        return_json(200,'成功',true);
      }else{
         return_json(400,'失败',false);
      }
    }


    public function delAll($ids){
     
       $res = self::destroy($ids[0]);
     if($res){
        foreach ($ids as $k => $v) {
            db('seckill_goods')->where('seckill_id',$v)->delete();
        }
           return_json(200,'成功',true);
       }else{
           return_json(400,'失败',false);
       }
    }

    public function detail($id){
       $res = self::where('id',$id)->find();
       if($res){
            return_json(200,'成功',$res);
        }else{
              return_json(400,'失败',false);
        }

    }

    public function edit($id,$data){
      $res = self::where('id',$id)->update($data);
     if($res){
            return_json(200,'成功',true);
        }else{
              return_json(400,'失败',false);
        }
    }

    public function status($id,$status){
      if($status == 1){
        $status = 0;
      }else{
        $status =1;
      }
      $res = self::where('id',$id)->update(['status'=>$status]);
      if($res){
            return_json(200,'成功',true);
        }else{
              return_json(400,'失败',false);
        }
    }

    public function selgoods($pagenum=1,$pagesize=1){

    $map =[];
    $keywords = Request::param('query');
    if(!empty($keywords)){
    //条件2
     $map[] = ['goods_title','like','%'.$keywords.'%'];
}
    
    $res = db('goods')->field('id,goods_title,goods_price')->where('on_sale',1)->where($map)->page($pagesize,$pagenum)->select();
    $count = model('goods')->where('on_sale',1)->count();

    $info = array(
      'data'=>$res,
      'total'=>$count
      );
    return_json(200,'成功',$info);

    }

    public function delgoods($gid,$id){
      $res = db('seckill_goods')->where('seckill_id',$id)->where('goods_id',$gid)->delete();
      if($res){
        $key = $id.'_goods_'.$gid;
        redis()->del($key);
        return_json(200,'成功',true);
        }
      else{
         return_json(400,'失败',false);
        }
    }

    public function goodsDetail($id){
      $res  = db('seckill_goods')->where('id',$id)->find();
      $goods = model('goods')->detail($res['goods_id']);
      $goods['goods_price'] = $res['sk_price'];
      $goods['inventory'] = $res['sk_num'];
      $goods['sk_id'] = $res['seckill_id'];
      return_json(200,'查询成功',$goods);
    }
    


}